package com.boruan.shengtangfeng.api.controller;

import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.dto.*;
import com.boruan.shengtangfeng.core.dto.mapper.TalkVideoDtoMapper;
import com.boruan.shengtangfeng.core.dto.mapper.UserAnswerDtoMapper;
import com.boruan.shengtangfeng.core.dto.mapper.VideoGradeDtoMapper;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.*;
import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import com.boruan.shengtangfeng.core.vo.mapper.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/school")
@Api(value = "学校班级",tags = "V4E-学校班级相关接口")
public class SchoolApi {

    @Autowired
    private ISchoolService schoolService;
    @Autowired
    private IClassParameterDao classParameterDao;
    @Autowired
    private IClassAndService classAndService;
    @Autowired
    private IClassMembersDao classMembersDao;
    @Autowired
    private IGroupChatDao groupChatDao;
    @Autowired
    private IGroupMembersDao groupMembersDao;
    @Autowired
    private IUserService userService;
    @Autowired
    private ChineseInital chineseInital;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuestionRecordService questionRecordService;
    @Autowired
    private IUserJobDao userJobDao;
    @Autowired
    private IVideoService videoService;
    @Autowired
    private IAttentionDao attentionService;
    @Autowired
    private IVideoCommentDao videoCommentService;
    @Autowired
    private IVideoGradeService videoGradeService;
    @Autowired
    private GradeUtil gradeUtil;
    @Autowired
    private IApplyForDao applyForDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private ISubjectDao subjectDao;
    @Autowired
    private IClassVideoMemberDao classVideoMemberDao;
    @Autowired
    private IClassInformMemberDao classInformMemberDao;
    @Autowired
    private IClassInformDao classInformDao;
    @Autowired
    private IInformDao informDao;
    @Autowired
    private IVideoDao videoDao;
    @Autowired
    private IUserFriendAndBlacklistDao userFriendAndBlacklistDao;
    @Autowired
    private IJobParameterDao jobParameterDao;
    @Autowired
    private TencentUtil tencentUtil;
    @Autowired
    private ALiYunUtils aLiYunUtils;


    @GetMapping("/getSchools")
    @ApiOperation(value = "V4E-001 查询学校列表",notes = "查询学校列表")
    public GlobalReponse<PageQuery<School>> getSchools(@ApiParam(value = "县区名") @RequestParam(value = "district",required = false) String district, @ApiParam(value = "关键词")@RequestParam(value = "keywords",required = false) String keywords, @RequestParam(value = "pageNo",defaultValue = "1") int pageNo){
        PageQuery<School> pageQuery = new PageQuery<School>(pageNo);
        School school = new School();
        school.setCounty(district);
        school.setName(keywords);
        pageQuery.setParas(school);
        return schoolService.getSchools(pageQuery);
    }

    @PostMapping("/getClassAnd")
    @ApiOperation(value = "V4E-002 查询班级列表【改】",notes = "查询班级列表")
    public GlobalReponse<PageQuery<ClassAndVo>> getClassAnd(@RequestBody ClassAndDto classAndDto){
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<ClassAnd> pageQuery = new PageQuery<ClassAnd>();
        pageQuery.setPageNumber(classAndDto.getPageNo());
        pageQuery.setPageSize(classAndDto.getPageSize());
        ClassAnd classAnd = new ClassAnd();
        classAnd.setSchoolId(classAndDto.getSchoolId());
        classAnd.setSchoolYear(classAndDto.getSchoolYear());
        if(classAndDto.getClassNum()!=""){
            classAnd.setClassNum(classAndDto.getClassNum());
        }
        if(classAndDto.getName()!=""){
            classAnd.setName(classAndDto.getName());
        }

        pageQuery.setParas(classAnd);
        return schoolService.getClassAnd(pageQuery,userSubject.getId());
    }

    @PostMapping("/getMyJoinClassName")
    @ApiOperation(value = "发布讲一讲时获取我加入的全部的班级")
    public GlobalReponse<List<MyJoinClassNameVo>> getMyJoinClassName(){
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        return schoolService.getMyJoinClassName(userId);
    }

    @GetMapping("/joinClassAnd")
    @ApiOperation(value = "V4E-021 加入班级")
    public GlobalReponse<User> joinClassAnd(@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId){
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());
        ClassAnd classAnd = classAndService.findById(classId);
        if(classAnd==null){
            return GlobalReponse.fail("班级查询失败");
        }
        ClassMembers classMembers = classAndService.findClassMember(userSubject.getId(),classId);
        if(classMembers!=null){
            return GlobalReponse.fail("您已加入班级");
        }
        ApplyFor single = applyForDao.createLambdaQuery().andEq(ApplyFor::getApplyId, user.getId()).andEq(ApplyFor::getRelevanceId, classAnd.getId()).andEq(ApplyFor::getType,2).andEq(ApplyFor::getStatus, 0).andEq(ApplyFor::getIsDeleted, false).single();
        if (single!=null){
            return GlobalReponse.fail("您已申请，请等待管理员同意");
        }
        ApplyFor applyFor = new ApplyFor();
        applyFor.setApplyId(user.getId());
        applyFor.setRelevanceId(classId);
        applyFor.setType(2);
        applyFor.setStatus(0);
        applyFor.setCreateTime(new Date());
        applyFor.setCreateBy(user.getId().toString());
        applyFor.setIsDeleted(false);
        applyForDao.insertTemplate(applyFor);
        return GlobalReponse.success("请等待管理员审核").setData(user);
    }

    @GetMapping("/schoolYear")
    @ApiOperation(value = "V4E-003学年配置【改】",notes = "学年配置")
    public GlobalReponse schoolYear(){

        String[] grade = {"一年级","二年级","三年级","四年级","五年级","六年级","七年级","八年级","九年级"};
        //获取学年配置
        ClassParameter classParam =classParameterDao.createLambdaQuery().andEq(ClassParameter::getId,1).unique();
        //获取当前年份
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //判断学制
        int num = classParam.getEducationSystem() == 1 ? 5 : 6;
        //判断上下学期
        String now = new SimpleDateFormat("MM-dd").format(new Date());
        String spring = classParam.getSpringTime();
        String autumn = classParam.getAutumnTime();
        int newYear=year+1;
        String nowTime = year+"-"+now;
        String springTime =year+"-"+spring;
        String autumnTime =newYear+"-"+autumn;

//        Date nowTime = null;
//        Date springTime = null;
//        Date autumnTime = null;
//        try {
//            nowTime = DateUtils.parseDate(now, "MM-dd");
//            springTime = DateUtils.parseDate(spring, "MM-dd");
//            autumnTime = DateUtils.parseDate(autumn, "MM-dd");
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        Date date = null;
        Date date1 = null;
        Date date2 = null;
        String item = null;
        try {
            date = DateUtils.parseDate(nowTime, "yyyy-MM-dd");
            date1 = DateUtils.parseDate(springTime, "yyyy-MM-dd");
            date2 = DateUtils.parseDate(autumnTime, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date.after(date1) && date.before(date2)) {
            item = "上";
        } else {
            item = "下";
        }
        ArrayList<Map> primary = new ArrayList<>();
        for(int i=0;i<num;i++){
            Map<String,String> map= new HashMap<String, String>();
            map.put("year",String.valueOf(year-i));
            map.put("name",(year-i)+"级("+grade[i]+item+")");
            primary.add(map);
        }

        ArrayList<Map> middle = new ArrayList<>();
        for(int y=num;y<9;y++){
            Map<String,String> map= new HashMap<String, String>();
            map.put("year",String.valueOf(year-y));
            map.put("name",(year-y)+"级("+grade[y]+item+")");
            middle.add(map);
        }
        return GlobalReponse.success("success").setData(primary).setData1(middle);
    }

    @PostMapping("/myClassAnd")
    @ApiOperation(value = "V4E-004 我的班级列表")
    public GlobalReponse<List<ClassAndVo>> myClassAnd(){
        //查询登录用户信息
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());
        List<ClassAnd> list = schoolService.myClassAnd(userSubject.getId());
        List<ClassAndVo> listVo = new ArrayList<>();
        if(!list.isEmpty()){
            for (ClassAnd v : list) {
                ClassAndVo vo = new ClassAndVo();
                vo.setClassId(v.getId());
                vo.setClassName(v.getName());
                vo.setClassNum(v.getClassNum());
                vo.setClassStatus(v.getStatus());
                GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId, v.getId()).andEq(GroupChat::getIsDeleted, false).single();
                if (groupChat.getTencentId()!=null){
                    vo.setTencentId(groupChat.getTencentId());
                }
                //查询创建人
                User creater = userService.findById(Long.valueOf(v.getCreateBy()));
                vo.setCreateName(creater.getName());
                vo.setCreateImage(creater.getHeadImage());
                vo.setCreateId(creater.getId());
                //查询班级人数
                Long memberNum = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId,v.getId()).count();
                vo.setMemberNum(memberNum);
                //查询学校信息
                School school = schoolService.findById(v.getSchoolId());
                vo.setSchoolId(school.getId());
                vo.setSchoolName(school.getName());
                vo.setProvince(school.getProvince());
                vo.setCity(school.getCity());
                vo.setCounty(school.getCounty());
                //处理学年格式
                ClassParameter classParam =classParameterDao.createLambdaQuery().andEq(ClassParameter::getId,1).unique();
                String schoolYear = gradeUtil.getGrade(Integer.valueOf(v.getSchoolYear()),classParam.getSpringTime(),classParam.getAutumnTime());
                vo.setGradeName(schoolYear);
                vo.setSchoolYear(v.getSchoolYear()+"级");
                //查询最新通知
                ClassInform classInform = classInformDao.createLambdaQuery().andEq(ClassInform::getClassId, v.getId()).andEq(ClassInform::getIsDeleted, false).desc(ClassInform::getCreateTime).single();
                if (classInform != null) {
                    Inform inform = informDao.unique(classInform.getInformId());
                    vo.setLastNotice(inform);
                    ClassInformMember single = classInformMemberDao.createLambdaQuery().andEq(ClassInformMember::getClassId, classInform.getClassId()).andEq(ClassInformMember::getInformId, classInform.getInformId()).andEq(ClassInformMember::getUserId, user.getId()).andEq(ClassInformMember::getIsDeleted, false).single();
                    if (single!=null){
                        if (single.getIsRead().equals(0)){
                            vo.setInformIsRead(0);
                        }else {
                            vo.setInformIsRead(1);
                        }
                    }else {
                        vo.setInformIsRead(0);
                    }
                }
                //查询最新三个作业
                List<Job> jobList = classAndService.last3Jobs(v.getId(),userSubject.getId());
                List<JobDto> jobDto = new ArrayList<>();
                for (Job job : jobList) {
                    UserJob userJob = userJobDao.createLambdaQuery().andEq(UserJob::getJobId, job.getId()).andEq(UserJob::getClassId, v.getId()).andEq(UserJob::getUserId, user.getId()).andEq(UserJob::getStatus, 0).andEq(UserJob::getIsDeleted, false).single();
                    if (userJob!=null){
                        if (jobDto.size()<3){
                            JobDto dto = new JobDto();
                            dto.setTopicNum(job.getQuestionNum());
                            dto.setJobId(job.getId());
                            dto.setStatus(userJob.getStatus());
                            dto.setJobName(job.getName());
                            dto.setDeadline(job.getDeadline());
                            dto.setDeadlineTime(job.getDeadline().getTime());
                            if (new Date().getTime() > job.getDeadline().getTime()) {
                                dto.setIsDeadline(true);
                            } else {
                                dto.setIsDeadline(false);
                            }
                            Subject subject = subjectDao.unique(job.getSubjectId());
                            dto.setSubjectName(subject.getName());
                            jobDto.add(dto);
                        }
                    }
                }
                vo.setClassJobDto(jobDto);
                vo.setClassJob(jobList);
                //处理讲一讲
                //讲一讲
                List<Video> newVideo = videoDao.getNewVideo(v.getId());
                ArrayList<VideoVo> videoVos = new ArrayList<>();
                if (!newVideo.isEmpty()) {
                    for (Video video : newVideo) {
                        ClassVideoMember single = classVideoMemberDao.createLambdaQuery().andEq(ClassVideoMember::getClassId, v.getId()).andEq(ClassVideoMember::getUserId, user.getId()).andEq(ClassVideoMember::getVideoId, video.getId()).andEq(ClassVideoMember::getIsDeleted, false).single();
                        if (single!=null){
                            if (single.getIsRead().equals(0)){
                                VideoVo videoVo = VideoVoMapper.MAPPER.toVo(video);
                                BigDecimal score = videoService.getVideoScore(videoVo.getId());
                                videoVo.setScore(score);
                                videoVos.add(videoVo);
                            }
                        }else {
                            VideoVo videoVo = VideoVoMapper.MAPPER.toVo(video);
                            BigDecimal score = videoService.getVideoScore(videoVo.getId());
                            videoVo.setScore(score);
                            videoVos.add(videoVo);
                        }
                    }
                    vo.setStudentVideo(videoVos);
                }
                listVo.add(vo);
            }
        }
        return GlobalReponse.success(listVo);
    }

    @PostMapping("/classInfo")
    @ApiOperation(value = "V4E-005  班级详情")
    public GlobalReponse<ClassAndVo> classInfo(@ApiParam(value = "班级ID")@RequestParam(value = "classId") Long classId){
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        ClassAnd classAnd = classAndService.findById(classId);
        ClassAndVo classAndVo = new ClassAndVo();
        ClassMembers single1 = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classId).andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).single();
        classAndVo.setMyNickname(single1.getNickname());
        classAndVo.setClassId(classAnd.getId());
        classAndVo.setClassStatus(classAnd.getStatus());
        classAndVo.setClassName(classAnd.getName());
        classAndVo.setClassNum(classAnd.getClassNum());
        //处理学年格式
        ClassParameter classParam =classParameterDao.createLambdaQuery().andEq(ClassParameter::getId,1).unique();
        String schoolYear = gradeUtil.getGrade(Integer.valueOf(classAnd.getSchoolYear()),classParam.getSpringTime(),classParam.getAutumnTime());
        classAndVo.setGradeName(schoolYear);
        classAndVo.setSchoolYear(classAnd.getSchoolYear());
        //查询学校信息
        School school = schoolService.findById(classAnd.getSchoolId());
        classAndVo.setSchoolName(school.getName());
        classAndVo.setProvince(school.getProvince());
        classAndVo.setCity(school.getCity());
        classAndVo.setCounty(school.getCounty());
        //查询教师人数和列表
        Long teacherNum = classAndService.countTeacher(classAnd.getId());
        List<ClassMembers> teacher = classAndService.teacherList(classAnd.getId());
        classAndVo.setTeacherList(teacher);
        classAndVo.setTeacherNum(teacherNum);
        //查询学生数量和列表
        Long studentNum = classAndService.countStudent(classAnd.getId());
        List<ClassMembers> student = classAndService.studentList(classAnd.getId());
        classAndVo.setStudentNum(studentNum);
        classAndVo.setStudentList(student);
        classAndVo.setMemberNum(teacherNum+studentNum);
        //查询讲一讲小视频列表
        //讲一讲
        List<Video> newVideo = videoDao.getNewVideo(classId);
        if (!newVideo.isEmpty()) {
            List<VideoVo> voList = VideoVoMapper.MAPPER.toVo(newVideo);
            for (VideoVo videoVo : voList) {
                BigDecimal score = videoService.getVideoScore(videoVo.getId());
                videoVo.setScore(score);
            }
            if (voList.size() > 10) {
                List<VideoVo> videoVos = voList.subList(0, 10);
                classAndVo.setStudentVideo(videoVos);
            } else {
                classAndVo.setStudentVideo(voList);
            }

        }
        //通知
        ClassInform classInform = classInformDao.createLambdaQuery().andEq(ClassInform::getClassId, classAnd.getId()).andEq(ClassInform::getIsDeleted, false).desc(ClassInform::getCreateTime).single();
        if (classInform != null) {
            Inform inform = informDao.unique(classInform.getInformId());
            classAndVo.setLastNotice(inform);
        }
        return GlobalReponse.success(classAndVo);
    }

    @PostMapping("/changeNickname")
    @ApiOperation(value = "V4E-006 修改班级内昵称")
    public GlobalReponse changeNickname(@ApiParam(value = "昵称")@RequestParam(value = "nickname")String nickname,@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId){
        UserSubject user = JwtUtil.getCurrentJwtUser();
        ClassMembers classMembers = classAndService.findClassMember(user.getId(),classId);
        classMembers.setNickname(nickname);
        classMembersDao.updateById(classMembers);
        return GlobalReponse.success("修改成功");
    }

    @GetMapping("/exitClass")
    @ApiOperation(value = "V4E-007 退出班级")
    public GlobalReponse exitClass(@ApiParam(value = "班级ID") @RequestParam(value = "classId")Long classId){
        UserSubject user = JwtUtil.getCurrentJwtUser();
        ClassMembers classMembers = classAndService.findClassMember(user.getId(),classId);
        GroupChat groupChat = groupChatDao.createLambdaQuery().andEq(GroupChat::getClassId,classMembers.getClassId()).andEq(GroupChat::getIsDeleted,false).unique();
        Boolean flag = tencentUtil.deleteGroupMember(groupChat.getId(), user.getId().toString());
        if (flag){
            classMembers.setIsDeleted(true);
            classMembersDao.updateById(classMembers);
            GroupMembers groupMembers=groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId,groupChat.getId()).andEq(GroupMembers::getUserId,user.getId()).unique();
            groupMembers.setIsDeleted(true);
            groupMembersDao.updateById(groupMembers);
            List<UserFriendAndBlacklist> select = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getType, 1).andEq(UserFriendAndBlacklist::getRelevanceId, groupChat.getId()).andEq(UserFriendAndBlacklist::getIsDeleted, false).select();
            for (UserFriendAndBlacklist andBlacklist : select) {
                andBlacklist.setIsDeleted(true);
                andBlacklist.setUpdateTime(new Date());
                andBlacklist.setUpdateBy(user.getId().toString());
                userFriendAndBlacklistDao.updateTemplateById(andBlacklist);
            }
            return GlobalReponse.success("退出成功");
        }
        return GlobalReponse.fail("退出失败");
    }

    @GetMapping("/classInform")
    @ApiOperation(value = "V4E-008 班级通知")
    public GlobalReponse<PageQuery<Inform>> classInform(@ApiParam(value = "班级Id")@RequestParam(value = "classId")Long classId,@RequestParam(value = "pageNo",defaultValue = "1")int pageNo,@ApiParam(value = "每页数量")@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        PageQuery<Inform> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setPara("classId",classId);
        classAndService.pageQueryClassInform(pageQuery);
        List<Inform> list = pageQuery.getList();
        List<InformDto> listVo = new ArrayList<>();
        for (Inform v : list) {
            ClassInformMember single = classInformMemberDao.createLambdaQuery().andEq(ClassInformMember::getClassId, classId).andEq(ClassInformMember::getInformId, v.getId()).andEq(ClassInformMember::getUserId, userId).andEq(ClassInformMember::getIsDeleted, 0).single();
            if (single!=null){
                single.setIsRead(1);
                classInformMemberDao.updateTemplateById(single);
            }else {
                ClassInformMember informMember = new ClassInformMember();
                informMember.setClassId(classId);
                informMember.setInformId(v.getId());
                informMember.setUserId(userId);
                informMember.setIsDeleted(false);
                informMember.setIsRead(1);
                informMember.setCreateTime(new Date());
                informMember.setCreateBy(userId.toString());
                classInformMemberDao.insertTemplate(informMember);
            }
            InformDto dto = new InformDto();
            User publisher = userService.findById(Long.valueOf(v.getCreateBy()));
            dto.setContent(v.getContent());
            dto.setCreateId(Long.valueOf(v.getCreateBy()));
            dto.setCreateNickname(publisher.getName());
            dto.setCreateImage(publisher.getHeadImage());
            dto.setImages(v.getImages());
            dto.setCreateTime(v.getCreateTime());
            dto.setId(v.getId());
            listVo.add(dto);
        }
        pageQuery.setList(listVo);
        return GlobalReponse.success(pageQuery);
    }

    @GetMapping("/classTeachers")
    @ApiOperation(value = "V4E-009 班级内教师列表")
    public GlobalReponse<List<ClassMemberVo>> classTeachers(@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId){
        UserSubject user = JwtUtil.getCurrentJwtUser();
        //查询班级成员
        List<ClassMembers> list = classAndService.teacherList(classId);
        List<ClassMemberVo> listVo = ClassMemberVoMapper.MAPPER.toVo(list);
        for (ClassMemberVo vo : listVo) {
            //判断是否好友
            Boolean isFriend = userService.isFriend(user.getId(),vo.getUserId());
            vo.setIsFriend(isFriend);
        }
        return GlobalReponse.success(listVo);
    }
//    shengtangfeng-api eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTY2NjgyMDg4NyIsInVpZCI6MTY2LCJvcGVuSWQiOm51bGwsImNyZWF0ZWQiOjE2MTg5ODg0NTcwODgsIm5hbWUiOiLlrZnogIHluIgiLCJpY29uIjoiaHR0cDovL3B1YmxpYy5zdGZ0dC5jb20vc2hlbmd0YW5nZmVuZy9wdWJsaWMvMjAyMTAzMTkvOGY0MTFiZTI0Mzk4NGY2ZGExODQ5MmE1YTBhOTUxZDUucG5nIiwiZXhwIjoxNjQ0OTA4NDU3fQ.58-uRLFq9uiVCdwSeLLAcHNBetX1ILTP2seqJbbHagNbBlAAuUoP0c7WlZpyPQHvfxQt-7LTGDkp3gBvbgQQXA
    @GetMapping("/classStudents")
    @ApiOperation(value = "V4E-010 班级里学生列表")
    public GlobalReponse classStudents(@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId){
        UserSubject user = JwtUtil.getCurrentJwtUser();

        //查询班级成员
        List<ClassMembers> list = classAndService.studentList(classId);
        List<ClassMemberVo> listVo = ClassMemberVoMapper.MAPPER.toVo(list);
        for (ClassMemberVo vo : listVo) {
            //判断是否好友
            Boolean isFriend = userService.isFriend(user.getId(),vo.getUserId());
            vo.setIsFriend(isFriend);
        }
        Map<String, List<ClassMemberVo>> res = listVo.stream()
                .collect(Collectors.groupingBy(firstLetter->{
                    return chineseInital.getFirstLetter(firstLetter.getNickname()).toUpperCase();
                },TreeMap::new,Collectors.toList()));
        ArrayList maps = new ArrayList<>();
        for (Map.Entry<String, List<ClassMemberVo>> entry : res.entrySet()) {
            Map map = new IdentityHashMap<>();
            map.put("letter",entry.getKey());
            map.put("list",entry.getValue());
            maps.add(map);
        }
        return GlobalReponse.success("查询成功").setData(maps);
    }

    @GetMapping("/classTeacherAndStudent")
    @ApiOperation(value = "V4E-011 班级里学生和老师列表")
    public GlobalReponse<Map<String, List<ClassMemberVo>>> classTeacherAndStudent(@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId){
        UserSubject user = JwtUtil.getCurrentJwtUser();

        //查询班级成员
        List<ClassMembers> teacherList = classAndService.teacherList(classId);
        List<ClassMemberVo> teacherListVo = ClassMemberVoMapper.MAPPER.toVo(teacherList);
        for (ClassMemberVo vo : teacherListVo) {
            //判断是否好友
            Boolean isFriend = userService.isFriend(user.getId(),vo.getUserId());
            vo.setIsFriend(isFriend);
            User unique = userDao.unique(vo.getUserId());
            vo.setAccount(unique.getAccount());
            vo.setMobile(unique.getMobile());

        }
        Map teacherMap = new IdentityHashMap<>();
        teacherMap.put("letter","教师");
        teacherMap.put("list",teacherListVo);


        //查询班级成员
        List<ClassMembers> list = classAndService.studentList(classId);
        List<ClassMemberVo> listVo = ClassMemberVoMapper.MAPPER.toVo(list);
        for (ClassMemberVo vo : listVo) {
            //判断是否好友
            Boolean isFriend = userService.isFriend(user.getId(),vo.getUserId());
            vo.setIsFriend(isFriend);
            User unique = userDao.unique(vo.getUserId());
            vo.setAccount(unique.getAccount());
            vo.setMobile(unique.getMobile());
        }
        Map<String, List<ClassMemberVo>> res = listVo.stream()
                .collect(Collectors.groupingBy(firstLetter->{
                    return chineseInital.getFirstLetter(firstLetter.getNickname()).toUpperCase();
                },TreeMap::new,Collectors.toList()));
        ArrayList maps = new ArrayList<>();
        maps.add(teacherMap);
        for (Map.Entry<String, List<ClassMemberVo>> entry : res.entrySet()) {
            Map map = new IdentityHashMap<>();
            map.put("letter",entry.getKey());
            map.put("list",entry.getValue());
            maps.add(map);
        }

        return GlobalReponse.success("查询成功").setData(maps).setData1(teacherListVo).setData2(listVo);
    }

    @GetMapping("/jobQuestion")
    @ApiOperation(value = "V4E-011 根据作业ID获取试题", notes = "")
    public GlobalReponse<List<Question>> jobQuestion(@ApiParam(value = "作业Id")@RequestParam(value = "jobId") Long jobId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Question> list = questionService.jobQuestion(jobId);
        for (Question question : list) {
            QuestionRecord condition = new QuestionRecord();
            condition.setUserId(userSubject.getId());
            condition.setQuestionId(question.getId());
            condition.setJobId(jobId);
            QuestionRecord record = questionRecordService.findByCondition(condition);
            if(record!=null){
                question.set("userAnswer",record);
            }else{
                question.set("userAnswer",null);
            }
            Boolean favoritesQuestion = questionService.isFavorites(userSubject.getId(),question.getId());
            question.set("isFavorite",favoritesQuestion);
            QuestionVo questionVo = QuestionVoMapper.MAPPER.toVo(question);
            question.set("optionList",questionVo.getOptionList());
            System.out.println(questionVo);
        }
        return GlobalReponse.success(list);
    }

    @PostMapping("/answerQuestion")
    @ApiOperation(value = "V4E-012 提交作业答案", notes = "")
    public GlobalReponse<Boolean> answerQuestion(@RequestBody UserAnswerDto userAnswerDto) {
        //查询用户信息
         UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());

        Question question = questionService.findById(userAnswerDto.getQuestionId());
        if(question==null){
            return GlobalReponse.fail("作业id错误");
        }
        QuestionRecord record = UserAnswerDtoMapper.MAPPER.toEntity(userAnswerDto);

        record.setUserId(userSubject.getId());

        QuestionRecord old = questionRecordService.hasAnswer(record);
        if (old != null) {
            record=old;
        }
        if(question.getType().getValue()!=null && question.getType().getValue()==0){
            if (userAnswerDto.getUserAnswer()!=null && StringUtils.equalsIgnoreCase(userAnswerDto.getUserAnswer(), question.getAnswer())) {
                record.setCorrect(true);
                record.setScore(question.getScore());
            }else {
                record.setCorrect(false);
                record.setScore(new BigDecimal(0));
            }
            record.setIsCheck(true);
            record.setStatus(1);
        }else {
            record.setIsCheck(false);
            record.setScore(new BigDecimal(0));
            if(question.getType().getValue()!=null && question.getType().getValue()!=2) {
                record.setStatus(1);
            }else{
                Boolean flag = aLiYunUtils.aliyunImageSyncCheck(userAnswerDto.getUserAnswer());
                if (flag){
                    record.setStatus(1);
                }else {
                    return GlobalReponse.success("图片存在敏感信息，请重新提交答案");
                }
            }
        }
        record.setUserAnswer(userAnswerDto.getUserAnswer());
        record.setCreateBy(user.getMobile());
        record.setUpdateTime(new Date());
        record.setIsDeleted(false);
        record.setUserId(user.getId());
        record.setUserName(user.getName());
        record.setAnswerType(question.getType().getValue());
        questionRecordService.save(record);
        //处理最终结果

        return GlobalReponse.success(record.getCorrect());
    }

    @PostMapping("/subJob")
    @ApiOperation(value = "V4E-020 完成作业")
    public GlobalReponse subJob(@RequestParam(value = "jobId") Long jobId,Long useTime,Long classId){
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        return questionRecordService.finishJobPush(jobId,userId,useTime,classId);
    }


    @PostMapping("/rank")
    @ApiOperation(value = "V4E-013 作业排行榜")
    public GlobalReponse<PageQuery<UserJobVo>> rank(@ApiParam(value = "班级id")@RequestParam(value = "classId")Long classId,@ApiParam(value = "作业ID")@RequestParam(value = "jobId")Long jobId,@ApiParam(value = "排行榜类型：1分数2速度3积极度")@RequestParam(value = "type")int type,@ApiParam(value = "页码")@RequestParam(value = "pageNo")int pageNo){
        //查询用户信息
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());

        UserJob my = userJobDao.createLambdaQuery().andEq(UserJob::getClassId,classId).andEq(UserJob::getJobId,jobId).andEq(UserJob::getUserId,user.getId()).unique();

        UserJobVo myVo = UserJobVoMapper.MAPPER.toVo(my);

        myVo.setFinishTime(format.format(my.getFinishTime()));
        myVo.setUserName(user.getName());
        myVo.setHeadImage(user.getHeadImage());
        myVo.setElapsedTime(my.getUseTime()*1000L);
        //查询作业信息
        Job job = classAndService.findJobById(jobId);
        PageQuery<UserJob> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPara("jobId",jobId);
        pageQuery.setPara("classId",classId);

        JobParameter single = jobParameterDao.createLambdaQuery().andEq(JobParameter::getIsDeleted, false).single();
        BigDecimal passScore = job.getScore().multiply(single.getAccuracy().divide(new BigDecimal(100)));

        if(type==1){
            classAndService.scoreRank(pageQuery);
            Long myRank = userJobDao.createLambdaQuery().andEq(UserJob::getJobId,jobId).andEq(UserJob::getStatus,2).andGreatEq(UserJob::getScore,my.getScore()).count();
            myVo.setRank(myRank);
        }else if(type==2){
            pageQuery.setPara("passScore",passScore);
            classAndService.speedRank(pageQuery);
            Long myRank = userJobDao.createLambdaQuery().andEq(UserJob::getJobId,jobId).andEq(UserJob::getStatus,2).andLess(UserJob::getUseTime,my.getUseTime()).andGreatEq(UserJob::getScore,passScore).count();
            myVo.setRank(myRank+1);
        }else{
            pageQuery.setPara("passScore",passScore);
            classAndService.submitRank(pageQuery);
            Long myRank = userJobDao.createLambdaQuery().andEq(UserJob::getJobId,jobId).andEq(UserJob::getStatus,2).andLess(UserJob::getFinishTime,my.getFinishTime()).andGreatEq(UserJob::getScore,passScore).count();
            myVo.setRank(myRank+1);
        }
        List<UserJob> list = pageQuery.getList();
        List<UserJobVo> listVo = UserJobVoMapper.MAPPER.toVo(list);
        for (UserJobVo vo : listVo) {
            UserJob userJob = userJobDao.unique(vo.getId());
            vo.setElapsedTime(userJob.getUseTime() * 1000L);
            if (userJob.getFinishTime() != null) {
                vo.setFinishTime(format.format(userJob.getFinishTime()));
            }
            User tempUser = userService.findById(vo.getUserId());
            vo.setUserName(tempUser.getName());
            vo.setHeadImage(tempUser.getHeadImage());
        }
        pageQuery.setList(listVo);
        return GlobalReponse.success().setData(myVo).setData1(pageQuery);
    }

    @PostMapping("/talkVideo")
    @ApiOperation(value = "V4E-015 班级讲一讲视频列表")
    public GlobalReponse<PageQuery<VideoVo>> talkVideo(@ApiParam(value = "班级ID")@RequestParam(value = "classId")Long classId,@ApiParam(value = "页码")@RequestParam(value = "pageNo")Integer pageNo,@RequestParam(value="pageSize",defaultValue = "10")int pageSize){
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        PageQuery<Video> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPageSize(10);
        pageQuery.setPara("classId",classId);
        videoService.pageClassTalkVideo(pageQuery);
        List<Video> list = pageQuery.getList();
        List<VideoVo> listVo = VideoVoMapper.MAPPER.toVo(list);
        for (VideoVo vo : listVo) {
            ClassVideoMember videoMember = new ClassVideoMember();
            videoMember.setClassId(classId);
            videoMember.setUserId(userId);
            videoMember.setVideoId(vo.getId());
            videoMember.setIsRead(1);
            videoMember.setIsDeleted(false);
            videoMember.setCreateBy(userId.toString());
            videoMember.setCreateTime(new Date());
            classVideoMemberDao.insertTemplate(videoMember);
            BigDecimal score = videoService.getVideoScore(vo.getId());
            Subject subject = subjectDao.unique(vo.getCategoryId());
            vo.setSubjectName(subject.getName());
            vo.setScore(score);
        }
        pageQuery.setList(listVo);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/saveVideo")
    @ApiOperation(value = "V4E-016 发布讲一讲视频", notes = "新增、修改保存")
    public GlobalReponse saveVideo(@RequestBody TalkVideoDto videoDto) throws IOException {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        if(videoDto.getScope()==2 && (videoDto.getClasses()==null || videoDto.getClass().equals(""))){
            return GlobalReponse.fail("请选择可见班级");
        }
        if(videoDto.getId()!=null) {
            Video video=videoService.findId(videoDto.getId());
            video.setScope(videoDto.getScope());
            video.setStatus(0);
            video.setCategoryId(videoDto.getCategoryId());
            video.setContent(videoDto.getContent());
            video.setTitle(videoDto.getTitle());
            video.setUploadType(1);
            video.setImage(video.getContent()+"?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
            videoService.saveSmall(video,videoDto.getClasses(),null,userSubject.getId(),videoDto.getClassId(),null);
        }else {
            Video video= TalkVideoDtoMapper.MAPPER.toEntity(videoDto);
            video.setPublishId(userSubject.getId());
            video.setPublisher(userSubject.getName());
            video.setPublisherIcon(userSubject.getIcon());
            video.setCreateBy(userSubject.getName());
            video.setCreateTime(new Date());
            video.setPublishDate(new Date());
            video.setStatus(0);
            video.setUploadType(1);
            video.setReadNum(0);
            video.setCommentNum(0);
            video.setThumpUpNum(0);
            video.setRecommend(false);
            video.setIsDeleted(false);
            video.setType(1);
            video.setImage(video.getContent()+"?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast");
            videoService.saveSmall(video,videoDto.getClasses(),null,userSubject.getId(),videoDto.getClassId(),null);
        }
        return GlobalReponse.success("发布成功");
    }

    @GetMapping("/talkVideoInfo")
    @ApiOperation(value = "V4E-017 讲一讲详情")
    public GlobalReponse<TalkVideoVo> talkVideoInfo(@ApiParam(value = "视频ID")@RequestParam(value = "videoId")Long videoId){
        UserSubject userSubject= JwtUtil.getCurrentJwtUser();
        Video video = videoService.findById(videoId);
        //获取一次详情加一次阅读量
        video.setReadNum((video.getReadNum()==null?0:video.getReadNum())+1);
        videoService.save(video);
        //是否关注
        Attention attention = null;
        VideoGrade myGrade = null;
        List<VideoComment> comments;
        ArrayList<String> scorePercent = new ArrayList<>();
        if(userSubject!=null) {
            //是否关注
            attention = attentionService.findByFocusId(userSubject.getId(),video.getPublishId());
            comments = videoCommentService.findByVideoId(userSubject.getId(),videoId, 1);
            //是否打分
            myGrade = videoGradeService.findUserGrade(userSubject.getId(),videoId);
        }else {
            comments = videoCommentService.findByVideoId(null,videoId, 1);
        }
        List<VideoCommentVo> commentVos= VideoCommentVoMapper.MAPPER.toVo(comments);
        //计算平均分
        BigDecimal score = videoService.avgScore(videoId);
        //计算各个分段百分比
        List<BigDecimal> percent = videoGradeService.getScorePercent(videoId);

        TalkVideoVo vo= TalkVideoVoMapper.MAPPER.toVo(video);
        vo.setIsAttention(null == attention ? false:true);
        vo.setComment(commentVos);
        vo.setScore(score);
        vo.setMyScore(myGrade);
        vo.setScorePercent(percent);
        if (vo.getPublishId()!=null){
            User unique = userDao.unique(vo.getPublishId());
            vo.setAccount(unique.getAccount());
        }

        return GlobalReponse.success(vo);
    }

    @GetMapping("/getTeacherGrade")
    @ApiOperation(value = "V4E-018 讲一讲教师打分列表")
    public GlobalReponse<List<VideoGrade>> getTeacherGrade(@ApiParam(value = "讲一讲ID")@RequestParam(value = "videoId")Long videoId){
        Video video = videoService.findId(videoId);
        if(null==video){
            return GlobalReponse.fail("讲一讲ID错误");
        }
        List<VideoGrade> list = videoGradeService.getTeacherGrade(video.getId());
        for (VideoGrade item : list) {
            User user = userService.findById(Long.valueOf(item.getCreateBy()));
            item.set("user",user);
        }
        return GlobalReponse.success(list);
    }

    @PostMapping("/getStudentGrade")
    @ApiOperation(value = "V4E-019 讲一讲学生打分列表")
    public GlobalReponse<PageQuery<VideoGrade>> getStudentGrade(@ApiParam(value = "讲一讲ID")@RequestParam(value = "videoId")Long videoId,@ApiParam(value = "页码")@RequestParam(value = "pageNo")int pageNo){
        PageQuery<VideoGrade> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPageSize(10);
        VideoGrade videoGrade = new VideoGrade();
        videoGrade.setVideoId(videoId);
        videoGrade.setStatus(1);
        videoGrade.setType(1);
        videoGrade.setIsDeleted(false);
        pageQuery.setParas(videoGrade);
        videoGradeService.getStudentGrade(pageQuery);
        List<VideoGrade> list = pageQuery.getList();
        for (VideoGrade item : list) {
            User user = userService.findById(Long.valueOf(item.getCreateBy()));
            item.set("user",user);
        }

        return GlobalReponse.success(pageQuery);
    }


    @PostMapping("/saveGrade")
    @ApiOperation(value = "V4E-020 保存讲一讲打分")
    public GlobalReponse saveGrade(@RequestBody VideoGradeDto videoGradeDto){
        UserSubject userSubject= JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());

        VideoGrade videoGrade = VideoGradeDtoMapper.MAPPER.toEntity(videoGradeDto);
        videoGrade.setUserId(user.getId());
        videoGrade.setType(user.getUserType());
        videoGrade.setCreateBy(user.getId().toString());
        videoGrade.setCreateTime(new Date());
        return videoGradeService.save(videoGrade);
    }

    @PostMapping("getJobListById")
    @ApiOperation(value = "V4E-021 查看班级作业列表", notes = "")
    public GlobalReponse<PageQuery<JobDto>> getJobList(@RequestBody JobConditionDto jobConditionDto) {
        if (jobConditionDto == null) {
            return GlobalReponse.fail("请传入正确的参数");
        }
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        return schoolService.getJobListById(jobConditionDto,userId);
    }
}
